package com.mzba.place.ui;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.MenuItem;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.search.MKAddrInfo;
import com.baidu.mapapi.search.MKBusLineResult;
import com.baidu.mapapi.search.MKDrivingRouteResult;
import com.baidu.mapapi.search.MKPoiResult;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.search.MKSearchListener;
import com.baidu.mapapi.search.MKSuggestionResult;
import com.baidu.mapapi.search.MKTransitRouteResult;
import com.baidu.mapapi.search.MKWalkingRouteResult;
import com.mzba.place.BasicActivity;
import com.mzba.place.PlaceApplication;
import com.mzba.place.R;
import com.mzba.place.entity.LocationInfo;
import com.mzba.place.ui.widget.CustomListView;
/**
 * 
 * @author 06peng
 *
 */
public class SearchAddressActivity extends BasicActivity {
	
	public MKSearch mSearch = null;
	public PlaceApplication app;
	
	private ArrayList<LocationInfo> infoList;
	private EditText addressEdit;
	private EditText cityEdit;
	private ImageView searchButton;
	private CustomListView listView;
	
	private AddressListAdapter adapter;
	private int latitude;
	private int longitude;
	private String address;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setSupportProgressBarIndeterminateVisibility(false);
		actionBar.show();
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setTitle("搜索位置");
		app = (PlaceApplication) getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            app.mBMapManager.init(PlaceApplication.strKey, new PlaceApplication.MyGeneralListener());
        }
        setContentView(R.layout.search_address);
        mSearch = new MKSearch();
        initMKSearch();
        initWidget();
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;

		default:
			break;
		}
		return false;
	}
	
	private void initWidget() {
		addressEdit = (EditText) findViewById(R.id.et_address);
		cityEdit = (EditText) findViewById(R.id.et_city);
		searchButton = (ImageView) findViewById(R.id.iv_address);
		searchButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (addressEdit.getText().toString().trim().equals("")) {
					Toast.makeText(SearchAddressActivity.this, "请输入地址！", Toast.LENGTH_LONG).show();
					return;
				} else if (cityEdit.getText().toString().trim().equals("")) {
					Toast.makeText(SearchAddressActivity.this, "请输入城市！", Toast.LENGTH_LONG).show();
					return;
				} else {
					mSearch.suggestionSearch(addressEdit.getText().toString().trim(), addressEdit.getText().toString().trim());
				}
			}
		});
		listView = (CustomListView) findViewById(R.id.list_address);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				LocationInfo info = infoList.get(arg2 - 1);
				mSearch.geocode(info.getLocationInfo(), info.getCity());
			}
		});
	}

	private void initMKSearch() {
		mSearch.init(app.mBMapManager, new MKSearchListener() {
			
			@Override
			public void onGetWalkingRouteResult(MKWalkingRouteResult res, int error) { }
			
			@Override
			public void onGetTransitRouteResult(MKTransitRouteResult res, int error) { }
			
			@Override
			public void onGetSuggestionResult(MKSuggestionResult res, int error) {
				if (error != 0 || res == null) {
					Toast.makeText(SearchAddressActivity.this, "抱歉，未找到结果！", Toast.LENGTH_LONG).show();
					return;
				}
				int nSize = res.getSuggestionNum();
				infoList = new ArrayList<LocationInfo>();

				for (int i = 0; i < nSize; i++) {
					LocationInfo info = new LocationInfo();
					info.setKey(res.getSuggestion(i).key);
					info.setCity(res.getSuggestion(i).city);
					infoList.add(info);
				}
				adapter = new AddressListAdapter();
				listView.setAdapter(adapter);
			}
			
			@Override
			public void onGetPoiResult(MKPoiResult arg0, int res, int error) { }
			
			@Override
			public void onGetPoiDetailSearchResult(int res, int error) { }
			
			@Override
			public void onGetDrivingRouteResult(MKDrivingRouteResult res, int error) { }
			
			@Override
			public void onGetBusDetailResult(MKBusLineResult res, int error) { }
			
			@Override
			public void onGetAddrResult(MKAddrInfo res, int error) {
				try {
					if (error != 0) {
						return;
					}
					if (res.geoPt != null) {
						latitude = res.geoPt.getLatitudeE6();
						longitude = res.geoPt.getLongitudeE6();
						address = res.strAddr;
						if (latitude != 0 && longitude != 0) {
							Intent intent = getIntent();
							intent.putExtra("latitude", latitude);
							intent.putExtra("longitude", longitude);
							intent.putExtra("address", address);
							setResult(RESULT_OK, intent);
							finish();
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
	}
	
	public class AddressListAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return infoList == null ? 0 : infoList.size();
		}

		@Override
		public Object getItem(int position) {
			return infoList == null ? null : infoList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = LayoutInflater.from(SearchAddressActivity.this).inflate(R.layout.empty_listitem, null);
			TextView tv = (TextView) convertView.findViewById(R.id.value);
			try {
				LocationInfo info = infoList.get(position);
				tv.setText(info.getLocationInfo());
			} catch (Exception e) {
				e.printStackTrace();
			}
			return convertView;
		}
		
	}
}
